<template>
  <el-switch
    :inactive-value="$props['inactiveValue']"
    :active-value="$props['activeValue']"
    :value="switchValue"
    class="cj-switch"
    @change="_clickCJSwitch"/>
</template>
<script>
export default {
  props: {
    beforeChangeSyncOtherParams: {
      type: Array,
      default: function() {
        return []
      }
    },
    beforeChangeSync: {
      type: Function,
      default: function(nextValue, prevValue) {
        return Promise.resolve(nextValue)
      }
    },
    value: {
      type: [Boolean, String, Number],
      default: false
    },
    change: {
      type: Function,
      default: function() {}
    },
    inactiveValue: {
      type: [Boolean, String, Number],
      default: false
    },
    activeValue: {
      type: [Boolean, String, Number],
      default: true
    }
  },
  data() {
    return {
      switchValue: this.$props.value
    }
  },
  watch: {
    value(val) {
      this.switchValue = val
    }
  },
  methods: {
    _clickCJSwitch() {
      var { inactiveValue = false, activeValue = true } = this.$props
      var {
        value: prevValue = false,
        beforeChangeSync,
        beforeChangeSyncOtherParams = []
      } = this.$props
      var nextValue = prevValue === inactiveValue ? activeValue : inactiveValue
      beforeChangeSync(nextValue, prevValue, ...beforeChangeSyncOtherParams).then(() => {
        this.switchValue = nextValue
        this.$emit('input', nextValue)
        this.$emit('change', nextValue)
      }).catch(exp => {
        this.switchValue = prevValue
      })
    }
  }
}
</script>

